package com.itheima.boottlias.interceptors;

import cn.hutool.core.util.StrUtil;
import com.itheima.boottlias.utils.JwtUtils;
import com.itheima.boottlias.utils.ThreadLocalUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author ghy
 * @version 1.0
 * @since 2025-07-17 16:07
 */
@Component
public class AuthorizedInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("AuthorizedInterceptor preHandle");
        // 4.不是，获取Token
        String token = request.getHeader("token");
        // 5.非空校验Token
        if(StrUtil.isBlank(token)) {
            // Token不存在
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        // 6.合法校验Token
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Object id = claims.get("id");
            System.out.println(id);
            // 把登录人ID绑定到ThreadLocal中
            ThreadLocalUtils.set((Integer) id);
            return true;
        } catch (Exception e) {
            // 非法Token
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 为了防止内存泄漏
        ThreadLocalUtils.remove();
    }
}
